package 动态规划;

/**
 * @author tmh
 * @date 2024/9/19 20:44
 * @description
 */
public class T72编辑距离 {
    public int minDistance(String word1, String word2) {
        //dp[i][j]表示以i-1为结尾的字符串和以j-1为结尾的字符串的最小编辑次数
        int m = word1.length();
        int n = word2.length();
        int[][] dp = new int[m + 1][n + 1];
        //初始化第一行和第一列
        for (int i = 0; i <= m; i++) {
            dp[i][0] = i;
        }
        //初始化第一列
        for (int j = 0; j <= n; j++) {
            dp[0][j] = j;
        }

        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                //看字符串中的字符是否相同
                if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i][j - 1], dp[i - 1][j])) + 1;
                }
            }
        }
        return dp[m][n];
    }
}
